package com.example.basic.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * ClassName: TokenUtil
 * Description:
 * date: 2021/12/14 10:28
 * author zesion lee
 */
@Slf4j
@Component
public class JwtUtil {
    private static String theSecretKey;

    @Value("${jwt.secretKey}")
    public void setKey(String secretKey) {
        theSecretKey = secretKey;
    }

    public static String createToken(Integer userId) throws JWTCreationException {
        Algorithm algorithm = Algorithm.HMAC512(theSecretKey);
        return JWT.create()
                .withIssuer("toprs")
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))
                .withClaim("userId", userId)
                .sign(algorithm);
    }

    public static String getUserId(String token) throws JWTDecodeException, TokenExpiredException {
        Algorithm algorithm = Algorithm.HMAC512(theSecretKey);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer("toprs").build(); //Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
        return String.valueOf(jwt.getClaim("userId"));
    }

}
